package org.eclipse.core.databinding.observable.value;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import org.eclipse.core.databinding.observable.Diffs;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.list.SingleSelection;

public class SingleSelectionObservableValue extends AbstractVetoableValue implements PropertyChangeListener{
  private SingleSelection selection;

  protected boolean updating = false;
  protected Object oldValue;
  
  public SingleSelectionObservableValue(SingleSelection selection) {
    this(Realm.getDefault(), selection);
  }
  public SingleSelectionObservableValue(Realm realm, SingleSelection selection) {
    super(realm);
    this.selection = selection;
    
    selection.addPropertyChangeListener("selected", this);
  }

  protected Object doGetValue() {
    return selection.getSelected();
  }

  public Object getValueType() {
    return selection.getElementType();
  }

  public void propertyChange(PropertyChangeEvent event) {
    if (!updating) {
      Object newValue = event.getNewValue();
      if (!newValue.equals(oldValue)){
        fireValueChange(Diffs.createValueDiff(oldValue, newValue));
        oldValue = newValue;
      }
    }
  }

  protected void doSetApprovedValue(Object value) {
    try {
      updating = true;
      
      oldValue = doGetValue();
    } finally {
      updating = false;
    }
  }
}
